package com.app.core;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;


import net.sf.json.JSONObject;
 
/**
 * 创建多个房间的访问
 * 
 * Msgs<br/>
 * @version 1.0.0<br/>
 *
 */
@ServerEndpoint("/video")
public class Msgs {
	
	private String username;//当前用户
	//所用用户通信管道
	private static List<Session> sessions = Collections.synchronizedList(new ArrayList());
	//所有用户列表
	private static List<String> users = Collections.synchronizedList(new ArrayList());
	
	/**
	 * @throws UnsupportedEncodingException 
	 * @Onopen 就是建立连接时触发的事件
	 * 获取登录信息
	 * 并且把用户添加到用户列表中
	 */
	@OnOpen
	public void open(Session session) throws UnsupportedEncodingException {
		
		String query = session.getQueryString();
		query = URLDecoder.decode(query, "utf-8");
		username = query.split("=")[1];
		//把每个session添加到用户通信管道里面去
		sessions.add(session);
		
		 if(!users.contains(username)) users.add(username);
		
		
		
		String msg = "欢迎" + username + "来到聊天室!";
		Message message = new Message();
		message.setWelcome(msg);
		message.setUsername(users);
		broadcast(sessions,JSONObject.fromObject(message).toString());
	}
	/**
	 * 发送广播
	 */
	public void broadcast(List<Session> boradcast, String msg) {
			try {
				if (sessions.size() != 0) {
	                for (Session s : sessions) {
	                    if (s != null) {
	                       s.getBasicRemote().sendText(msg);
	                    }
	                }
	            }
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	/**
	 * 接收前端传来的消息/发送消息
	 */
	@OnMessage
	public void onMessage(String msg, Session session) {
		System.out.println("前端发送的消息为："+msg);
		Message message = new Message();
		//message.setUsername(users);
		message.setContext(username, msg);
		broadcast(sessions,JSONObject.fromObject(message).toString());
	}
	 /*
     * 客户端断开链接后将其从线程安全的集合中移除
     */
    @OnClose
    public void onClose(Session session) {
        sessions.remove(session);
    }
}
